package org.hbgl.geoentity.admin.web.admin;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.hbgl.geoentity.admin.annotation.OperationLog;
import org.hbgl.geoentity.admin.annotation.RequiresPermissionsDesc;
import org.hbgl.geoentity.admin.aspect.OperationType;
import org.hbgl.geoentity.admin.shiro.UserType;
import org.hbgl.geoentity.admin.web.BaseController;
import org.hbgl.geoentity.core.util.JacksonUtil;
import org.hbgl.geoentity.core.util.RegexUtil;
import org.hbgl.geoentity.core.util.ResponseUtil;
import org.hbgl.geoentity.core.util.bcrypt.BCryptPasswordEncoder;
import org.hbgl.geoentity.db.domain.GeDepartment;
import org.hbgl.geoentity.db.domain.GeRole;
import org.hbgl.geoentity.db.domain.GeUser;
import org.hbgl.geoentity.db.util.EnumFile;
import org.hbgl.geoentity.db.vo.UserVo;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;

import static org.hbgl.geoentity.admin.util.ResponseCode.*;

/**
 * 代码功能：账号管理
 * 开发日期：2022/4/26
 * 作者：蒋海仑
 * 联系方式：
 * 版本更迭说明：
 * 版权信息：河北广联信息技术有限公司
 */
@RestController
@RequestMapping("/admin/user")
@Validated
public class AdminUserController extends BaseController {

    //region 系统设置--账号管理

    /**
     * 获取账号列表
     *
     * @param keywords 模糊查询
     * @param page     页码
     * @param limit    分页大小
     */
    @RequiresPermissions("admin:user:list")
    @RequiresPermissionsDesc(menu = {"系统设置", "账号管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(@RequestParam(defaultValue = "0") Integer roleId,
                       @RequestParam(defaultValue = "") String keywords,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit) {
        GeUser userCurrent = getCurrentAdminUser();
        List<UserVo> userList = userService.selectUserList(userCurrent.getUnitId(), roleId, keywords, page, limit);
        for(UserVo item: userList) {
            if(userCurrent.getId().equals(item.getId())) {
                item.setIsOperate(1);
            }else {
                item.setIsOperate(0);
            }
        }
        return ResponseUtil.okList(userList);
    }

    /**
     * 根据账号ID获取账号信息
     *
     * @param id 账号ID
     */
    @RequiresPermissions("admin:user:detail")
    @RequiresPermissionsDesc(menu = {"系统设置", "账号管理"}, button = "详情")
    @GetMapping("/detail")
    public Object detail(@NotNull Integer id) {
        GeUser userCurrent = getCurrentAdminUser();

        UserVo userLatest = userService.selectUserById(userCurrent.getUnitId(), id);
        if (userLatest == null) {
            return ResponseUtil.badArgumentValue();
        }

        return ResponseUtil.ok(userLatest);
    }

    /**
     * 新建账号
     *
     * @param user 账号信息
     */
    @RequiresPermissions("admin:user:create")
    @RequiresPermissionsDesc(menu = {"系统设置", "账号管理"}, button = "新建")
    @OperationLog(detail = "新建账号", operationType = OperationType.INSERT, userType = UserType.ADMIN)
    @PostMapping("/create")
    public Object create(@RequestBody GeUser user) {
        Integer roleId = user.getRoleId();
        String username = user.getUsername();
        String password = user.getPassword();
        // Integer departmentId = user.getDepartmentId();
        if (!ObjectUtils.allNotNull(
                roleId, username, password
        )) {
            return ResponseUtil.badArgument();
        }
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return ResponseUtil.badArgumentValue();
        }
        if (!RegexUtil.isUsername(username)) {
            return ResponseUtil.fail(USER_INVALID_NAME, "账号不符合规定(范围：“a-z”、“a-z”、“0-9”、“_”、“汉字”，不能以“_”结尾，长度在6到20之间)");
        }
        if (password.length() < 6) {
            return ResponseUtil.fail(USER_INVALID_PASSWORD, "密码长度不能小于6");
        }

        GeUser userCurrent = getCurrentAdminUser();

        List<GeUser> userList = userService.findByUsernameCheck(username, true);
        if (userList.size() > 0) {
            return ResponseUtil.fail(USER_NAME_EXIST, "账号已经存在");
        }

        user.setUnitId(userCurrent.getUnitId());
        user.setRoleId(roleId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.setPassword(encoder.encode(password));
        userService.add(user);

        return ResponseUtil.ok();
    }

    /**
     * 编辑账号信息
     *
     * @param user 账号信息
     */
    @RequiresPermissions("admin:user:update")
    @RequiresPermissionsDesc(menu = {"系统设置", "账号管理"}, button = "编辑")
    @OperationLog(detail = "编辑账号信息", operationType = OperationType.UPDATE, userType = UserType.ADMIN)
    @PostMapping("/update")
    public Object update(@RequestBody GeUser user) {
        Integer id = user.getId();
        Integer roleId = user.getRoleId();
        // Integer departmentId = user.getDepartmentId();
        if (!ObjectUtils.allNotNull(
                id, roleId
        )) {
            return ResponseUtil.badArgument();
        }

        GeUser userCurrent = getCurrentAdminUser();

        GeUser userLatest = userService.findById(userCurrent.getUnitId(), id);
        if (userLatest == null) {
            return ResponseUtil.badArgumentValue();
        }

        // GeDepartment department = departmentService.findById(userCurrent.getUnitId(), departmentId);
        // if (department == null) {
        //     return ResponseUtil.badArgumentValue();
        // }
        GeRole role = roleService.findById(userCurrent.getUnitId(), roleId);
        if (role == null) {
            return ResponseUtil.badArgumentValue();
        }

        userLatest.setRoleId(user.getRoleId());
        // userLatest.setDepartmentId(user.getDepartmentId());
        userLatest.setRealname(user.getRealname());
        userLatest.setSex(user.getSex());
        userLatest.setTelephone(user.getTelephone());
        userLatest.setEmail(user.getEmail());
        if (!ObjectUtils.allNotNull(user.getPassword())) {
            userLatest.setPassword(user.getPassword());
        }

        if (userService.updateByIdSelective(userLatest) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok();
    }

    /**
     * 启用/禁用账号
     *
     * @param body { id : 单位ID, state : 状态 }
     */
    @RequiresPermissions("admin:user:state")
    @RequiresPermissionsDesc(menu = {"系统设置", "账号管理"}, button = "启用/禁用")
    @OperationLog(detail = "启用/禁用账号", operationType = OperationType.UPDATE, userType = UserType.ADMIN)
    @PostMapping("/state")
    public Object state(@RequestBody String body) {
        Integer id = JacksonUtil.parseInteger(body, "id");
        Integer state = JacksonUtil.parseInteger(body, "state");
        if (!ObjectUtils.allNotNull(id, state)) {
            return ResponseUtil.badArgument();
        }
        if (state != EnumFile.CommonState.Normal && state != EnumFile.CommonState.Disable) {
            return ResponseUtil.badArgumentValue();
        }

        GeUser userCurrent = getCurrentAdminUser();
        if (userCurrent.getId().equals(id)) {
            return ResponseUtil.fail(USER_DELETE_NOT_ALLOWED, "不能启用/禁用自己账号");
        }

        GeUser userLatest = userService.findById(userCurrent.getUnitId(), id);
        if (userLatest == null) {
            return ResponseUtil.badArgumentValue();
        }
        GeUser user = new GeUser();
        user.setId(id);
        user.setState(state);

        if (userService.updateByIdSelective(user) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok();
    }

    /**
     * 重置密码
     *
     * @param body { id : 账号ID, password : 新密码 }
     */
    @RequiresPermissions("admin:user:password")
    @RequiresPermissionsDesc(menu = {"系统设置", "账号管理"}, button = "重置密码")
    @OperationLog(detail = "重置密码", operationType = OperationType.UPDATE, userType = UserType.ADMIN)
    @PostMapping("/password")
    public Object password(@RequestBody String body) {
        Integer id = JacksonUtil.parseInteger(body, "id");
        String password = JacksonUtil.parseString(body, "password");
        if (!ObjectUtils.allNotNull(id, password)) {
            return ResponseUtil.badArgument();
        }
        if (password.length() < 6) {
            return ResponseUtil.fail(ADMIN_INVALID_PASSWORD, "密码长度不能小于6");
        }

        GeUser userCurrent = getCurrentAdminUser();

        GeUser userLatest = userService.findById(userCurrent.getUnitId(), id);
        if (userLatest == null) {
            return ResponseUtil.badArgumentValue();
        }

        GeUser user = new GeUser();
        user.setId(id);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.setPassword(encoder.encode(password));

        if (userService.updateByIdSelective(user) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok();
    }

    //endregion

}
